toastLog("版本：24.10.10");
FloatyUtil(); //=悬浮窗加载===
init();
let height = device.height;
let width = device.width;
var qq = require("/sdcard/脚本/QQ");
qq.init();

let 多线程 = threads.start(function () {
  sleep(3000);
  let start = widgetGetOne("允许|立即开始|取消");
  if (start && "取消" == start.text()) {
    click(start.bounds().centerX() + 200, start.bounds().centerY());
  } else if (start) {
    clickCenter(start);
  }
});
if (!requestScreenCapture()) {
  toast("请求截图失败");
  exit();
}
多线程.interrupt();
home();
sleepT(5, "5秒后开始");
launch("com.tencent.mm");
findAndClick("允许|打开");
sleepT(8, "等待微信启动");
if (!findAndClick("发现", 8000, 3000)) {
  log("没有查询到发现重新查询");
  home();
  launch("com.tencent.mm");
  findAndClick("发现");
}
if (!findAndClick("小程序", 8000, 3000)) {
  log("没有查询到小程序重新查询");
  home();
  launch("com.tencent.mm");
  findAndClick("小程序");
}
findAndClick("朴朴超市", 8000, 3000);
sleepT(15, "等待加载广告~·");

let 我的 = 找字(/我的/);
if (我的) {
  click(我的.x, 我的.y);
  sleepT(2);
  click(我的.x, 我的.y);
  sleepT(1);
  click(我的.x, 我的.y);
  sleepT(1);
  click(我的.x, 我的.y);
  sleepT(1);
  click(我的.x, 我的.y);
}
let 更多 = widgetGetOne("更多");
findAndClick("退款.*", 16000);
sleep(5000);
back();
findAndClick("退款.*", 16000);
sleepT(5);
let 开扭 = 找字(/开扭|一起|组队/);
if (开扭) {
  click(开扭.x, 开扭.y);
  sleep(4000);
  log("开始第二次点击");
  click(开扭.x, 开扭.y);
} else {
  findAndClick(".*一起.*");
  findAndClick("再邀3人瓜分", 8000, 3000);
}
clickCenter(更多);
findAndClick("坐看.*", 8000, 4000);
findAndClick("发送到聊天", 8000, 3000);
退出();

助力("com.tencent.mn5");
助力("com.tencent.mn1");
助力("com.tencent.mn7");
助力("com.tencent.mn8");
function 助力(mn1) {
  console.error("启动app:" + mn1);
  if (!launch(mn1)) {
    sleepT(4, "第一次启动失败,4秒后再尝试打开");
    launch(mn1);
  }
  findAndClick("打开|允许|取消");
  sleepT(15, "等待15秒同步数据");
  findAndClick("发现");
  findAndClick("微信");
  if (!findAndClick(".*一起拿朴分.*")) {
    launch(mn1);
    sleepT(4, "第一次启动失败,4秒后再尝试打开");
    findAndClick(".*一起拿朴分.*");
  }
  sleep(2000);
  let 一起拿朴分 = textContains("一起拿朴分").find();
  log(一起拿朴分.length);
  if (一起拿朴分.length > 0) {
    clickView(一起拿朴分[一起拿朴分.length - 1]);
    sleepT(15, "等待5秒");
    back();
    sleep(1000);
    clickView(一起拿朴分[一起拿朴分.length - 1]);
  }

  if (!findAndClick("立即参.", 16000, 6000)) {
    let 一起拿朴分 = textContains("一起拿朴分").find();
    log(一起拿朴分.length);
    if (一起拿朴分.length > 0) {
      clickView(一起拿朴分[一起拿朴分.length - 1]);
    }
    back();
    sleep(1000);
    clickView(一起拿朴分[一起拿朴分.length - 1]);
    findAndClick("立即参.", 16000, 4000);
  }
  try {
    className("android.widget.TextView").text("").findOnce().click();
  } catch (error) {
    console.warn("没有查询到关闭控件当前app:" + mn1);
  }

  sleepT(5);
  退出();
}
/**
 * 根据内容获取一个对象
 *
 * @param {string} contentVal
 * @param {number} timeout 默认超时时间5秒
 * @param {boolean} containType 是否带回类型
 * @param {boolean} suspendWarning 是否隐藏warning信息
 * @param {function} appendFilter 附加查询条件 详见UiSelector
 */
function widgetGetOne(contentVal, timeout, containType, suspendWarning, appendFilter, options) {
  let target = null;
  let isDesc = false;
  let waitTime = timeout || 8000;
  let timeoutFlag = true;
  showFLog("try to find one: " + contentVal.toString() + "timeout: " + waitTime + "ms");
  let checkResult = widgetCheck(contentVal, waitTime, true, appendFilter, options);
  if (!checkResult.timeout) {
    timeoutFlag = false;
    target = checkResult.target;
    isDesc = checkResult.isDesc;
  }
  // 当需要带回类型时返回对象 传递target以及是否是desc
  if (target && containType) {
    let result = {
      target: target,
      bounds: target.bounds(),
      isDesc: isDesc,
      content: isDesc ? target.desc() : target.text(),
    };
    return result;
  }
  return target;
}

/**
 * 替换控件搜索算法DFS,BFS,VDFS,VBFS,PDFS,PBFS,PVDFS,PVBFS
 * DFS,BFS为默认提供的深度优先和广度优先搜索算法
 * VDFS,VBFS为我修改的只搜索可见控件（控件包括父级不可见则直接跳过）深度优先和广度优先搜索算法 缺点是无法搜索不可见控件，适合一个界面中有巨量控件的时候用于加快搜索速度 实际数据抖音极速版从25s缩短到3s
 * PDFS,PBFS,PVDFS,PVBFS 是通过多线程搜索控件 大大加快搜索速度
 *
 * @param {string} algorithm 搜索算法DFS,BFS,VDFS,VBFS,PDFS,PBFS,PVDFS,PVBFS
 * @param {UiSelector} mselector
 * @returns
 */
function wrapSelector(algorithm, appendFilter, mselector) {
  appendFilter =
    appendFilter ||
    function (matcher) {
      return matcher;
    };
  mselector = appendFilter(mselector || selector());
  if (!algorithm) {
    return mselector;
  }
  if (!algorithm_change_support) {
    log(["当前版本不支持替换搜索算法"]);
    return mselector;
  }
  current = this.getCurrentAlgorithm();
  if (current == algorithm) {
    return mselector;
  }
  log(["替换搜索算法为：{} 原始算法：{}", algorithm, current]);
  return AlgorithmChanger.changeAlgorithm(mselector, algorithm);
}

/**
 * 查找一个子控件中的目标对象
 * @param {UiObject} container 父控件
 * @param {String} contentVal 控件文本
 * @param {number} timeout 超时时间 默认5秒
 * @param {Boolean} containType 返回结果附带文本是desc还是text
 * @param {function} appendFilter 附加查询条件 详见UiSelector
 * @param {Object} options 额外参数
 * 超时返回false
 */
function subWidgetGetOne(container, contentVal, timeout, containType, appendFilter, options) {
  options = options || {};
  timeout = timeout || 8000;
  let countDown = new java.util.concurrent.CountDownLatch(1);
  let matchRegex = new RegExp(contentVal);
  let isDesc = false;
  let isText = false;
  let target = null;
  let descThread = threads.start(function () {
    let descTarget = wrapSelector(options.algorithm, appendFilter).descMatches(matchRegex).findOneOf(container);
    if (descTarget) {
      log("find desc " + contentVal + " " + descTarget.desc());
      isDesc = true;
      target = descTarget;
      countDown.countDown();
    }
  });

  let textThread = threads.start(function () {
    let textTarget = wrapSelector(options.algorithm, appendFilter).textMatches(matchRegex).findOneOf(container);
    if (textTarget) {
      log("find text " + contentVal + " " + textTarget.desc());
      isText = true;
      target = textTarget;
      countDown.countDown();
    }
  });

  let isTimeout = false;
  let timeoutThread = threads.start(function () {
    sleep(timeout);
    isTimeout = true;
    countDown.countDown();
  });

  countDown.await();
  descThread.interrupt();
  textThread.interrupt();
  timeoutThread.interrupt();
  if (isTimeout || (!isDesc && !isText)) {
    showFLog("cannot find any matches " + contentVal);
  }
  if (target && containType) {
    return {
      isDesc: isDesc,
      target: target,
      bounds: target.bounds(),
      content: isDesc ? target.desc() : target.text(),
    };
  }
  return target;
}

/**
 * 查找一个子控件中的目标对象
 * @param {UiObject} container 父控件
 * @param {String} contentVal 控件id
 * @param {number} timeout 超时时间 默认5秒
 * @param {Boolean} containType 返回结果附带文本是desc还是text
 * @param {function} appendFilter 附加查询条件 详见UiSelector
 * @param {Object} options 额外参数
 * 超时返回false
 */
function subWidgetGetById(container, contentVal, timeout, containType, appendFilter, options) {
  options = options || {};
  timeout = timeout || 5000;
  let countDown = new java.util.concurrent.CountDownLatch(1);
  let matchRegex = new RegExp(contentVal);
  let isDesc = false;
  let isText = false;
  let target = null;
  let descThread = threads.start(function () {
    let descTarget = wrapSelector(options.algorithm, appendFilter).id(matchRegex).findOneOf(container);
    if (descTarget) {
      log(["find id " + contentVal + " " + descTarget.desc()]);
      isDesc = true;
      target = descTarget;
      countDown.countDown();
    }
  });

  let isTimeout = false;
  let timeoutThread = threads.start(function () {
    sleep(timeout);
    isTimeout = true;
    countDown.countDown();
  });

  countDown.await();
  descThread.interrupt();
  timeoutThread.interrupt();
  if (isTimeout || (!isDesc && !isText)) {
    showFLog("cannot find any matches " + contentVal);
  }
  if (target && containType) {
    return {
      isDesc: isDesc,
      target: target,
      bounds: target.bounds(),
      content: isDesc ? target.desc() : target.text(),
    };
  }
  return target;
}

/**
 * 校验控件是否存在，并打印相应日志
 * @param {String} idRegex 控件文本
 * @param {String} position 日志内容 当前所在位置是否成功进入
 * @param {Number} timeoutSetting 超时时间 默认为 5秒
 */
function idWaiting(idRegex, position, timeoutSetting, appendFilter, options) {
  options = options || {};
  let waitingSuccess = idCheck(idRegex, timeoutSetting, false, appendFilter, options);
  position = position || idRegex;
  if (waitingSuccess) {
    showFLog("等待控件成功：" + position);
    return true;
  } else {
    showFLog("等待控件[" + position + "]失败， id：" + idRegex);
    return false;
  }
}

/**
 * id检测
 * @param {string|RegExp} idRegex
 * @param {number} timeoutSetting
 */
function idCheck(idRegex, timeoutSetting, containType, appendFilter, options) {
  options = options || {};
  let timeout = timeoutSetting || 5000;
  let timeoutFlag = true;
  let countDown = new java.util.concurrent.CountDownLatch(1);
  let target = null;
  let idCheckThread = threads.start(function () {
    target = wrapSelector(options.algorithm, appendFilter).idMatches(idRegex).findOne();
    showFLog("find id " + idRegex);
    timeoutFlag = false;
    countDown.countDown();
  });

  let timeoutThread = threads.start(function () {
    sleep(timeout);
    countDown.countDown();
  });
  countDown.await();
  idCheckThread.interrupt();
  timeoutThread.interrupt();
  if (timeoutFlag) {
    log("未能找到id:" + idRegex + "对应的控件");
  }
  if (containType) {
    return {
      timeout: timeoutFlag,
      target: target,
      bounds: target ? target.bounds() : null,
    };
  }
  return !timeoutFlag;
}

/**
 * 校验控件是否存在
 * @param {String} contentVal 控件文本
 * @param {Number} timeoutSetting 超时时间 单位毫秒
 * @param {Boolean} containType 返回结果附带文本是desc还是text
 * @param {Object} options 额外参数
 * 超时返回false
 */
function widgetCheck(contentVal, timeoutSetting, containType, appendFilter, options) {
  options = options || {};
  let timeout = timeoutSetting || 8000;
  let timeoutFlag = true;
  let countDown = new java.util.concurrent.CountDownLatch(1);
  let matchRegex = new RegExp(contentVal);
  let isDesc = false;
  let target = null;
  let descThread = threads.start(function () {
    target = wrapSelector(options.algorithm, appendFilter).descMatches(matchRegex).findOne();
    let res = target.desc();
    showFLog("find desc " + contentVal + " " + res);
    timeoutFlag = false;
    isDesc = true;
    countDown.countDown();
  });

  let textThread = threads.start(function () {
    target = wrapSelector(options.algorithm, appendFilter).textMatches(matchRegex).findOne();
    let res = target.text();
    showFLog("find text " + contentVal + "  " + res);
    timeoutFlag = false;
    countDown.countDown();
  });

  let timeoutThread = threads.start(function () {
    sleep(timeout);
    log("等待查询:" + contentVal + " 超时");
    countDown.countDown();
  });
  countDown.await();
  descThread.interrupt();
  textThread.interrupt();
  timeoutThread.interrupt();
  if (timeoutFlag) {
    showFLog("cannot find any matches " + contentVal + " timeout:" + timeout);
  }
  if (containType) {
    return {
      timeout: timeoutFlag,
      target: target,
      bounds: target ? target.bounds() : null,
      isDesc: isDesc,
    };
  }
  return !timeoutFlag;
}

/**
 * 校验控件是否存在，并打印相应日志
 * @param {String} contentVal 控件文本
 * @param {String} position 日志内容 当前所在位置是否成功进入
 * @param {Number} timeoutSetting 超时时间 单位毫秒 默认为_config.timeout_existing
 */
function widgetWaiting(contentVal, position, timeoutSetting, appendFilter, options) {
  options = options || {};
  let waitingSuccess = widgetCheck(contentVal, timeoutSetting, false, appendFilter, options);
  position = position || contentVal;
  if (waitingSuccess) {
    showFLog("等待控件成功：" + position);
    return true;
  } else {
    showFLog("等待控件[" + position + "]失败, 查找内容：" + contentVal);
    return false;
  }
}

/**
 * 根据id获取控件信息
 * @param {String|RegExp} idRegex id
 * @param {number} timeout 超时时间
 * @return 返回找到的控件，否则null
 */
function widgetGetById(idRegex, timeout, appendFilter, options) {
  options = options || {};
  timeout = timeout || 5000;
  let target = idCheck(idRegex, timeout, true, appendFilter, options);
  if (!target.timeout) {
    return target.target;
  } else {
    return null;
  }
}

function clickCenter(obj, x, y) {
  x = x || 0;
  y = y || 0;
  if (obj.bounds().centerX() > width || obj.bounds().centerY() > height || obj.bounds().centerX() < 0 || obj.bounds().centerY() < 0) {
    log("不可点击范围:" + obj.bounds().centerX() + " " + obj.bounds().centerY() + " 额外" + x + "," + y);
    return true;
  }
  log(obj.text() + " 点击位置：" + Number(obj.bounds().centerX() + x) + " " + Number(obj.bounds().centerY() + y));
  click(Number(obj.bounds().centerX() + x), Number(obj.bounds().centerY() + y));
  return false;
}

/**
 * 判断控件A或者控件B是否存在；超时返回0 找到A返回1 否则返回2
 *
 * @param {string|regex} contentA 控件A的内容
 * @param {string|regex} contentB 控件B的内容
 * @param {number} timeout 超时时间
 * @param {boolean} containContent 是否传递实际内容
 * @param {function} appendFilter 附加查询条件 详见UiSelector
 * @param {object} options 额外参数
 * @return 超时返回0 找到A返回1 否则返回2
 */
function alternativeWidget(contentA, contentB, timeout, containContent, appendFilter, options) {
  options = options || {};
  timeout = timeout || _config.timeout_existing;
  let timeoutFlag = true;
  let countDown = new java.util.concurrent.CountDownLatch(1);
  let matchRegexA = new RegExp(contentA);
  let matchRegexB = new RegExp(contentB);
  let isDesc = false,
    findA = false;
  let res = null,
    target = null;
  let descThreadA = threads.start(function () {
    target = wrapSelector(options.algorithm, appendFilter).descMatches(matchRegexA).findOne();
    res = target.desc();
    console.info("find desc " + contentA + " " + res);
    timeoutFlag = false;
    isDesc = true;
    findA = true;
    countDown.countDown();
  });

  let textThreadA = threads.start(function () {
    target = wrapSelector(options.algorithm, appendFilter).textMatches(matchRegexA).findOne();
    res = target.text();
    console.info("find text " + contentA + "  " + res);
    timeoutFlag = false;
    findA = true;
    countDown.countDown();
  });
  let descThreadB = threads.start(function () {
    target = wrapSelector(options.algorithm, appendFilter).descMatches(matchRegexB).findOne();
    res = target.desc();
    console.info("find desc " + contentB + " " + res);
    timeoutFlag = false;
    isDesc = true;
    countDown.countDown();
  });

  let textThreadB = threads.start(function () {
    target = wrapSelector(options.algorithm, appendFilter).textMatches(matchRegexB).findOne();
    res = target.text();
    console.info("find text " + contentB + "  " + res);
    timeoutFlag = false;
    countDown.countDown();
  });

  let timeoutThread = threads.start(function () {
    sleep(timeout);
    countDown.countDown();
  });
  countDown.await();
  descThreadA.interrupt();
  textThreadA.interrupt();
  descThreadB.interrupt();
  textThreadB.interrupt();
  timeoutThread.interrupt();
  if (timeoutFlag) {
    console.info("cannot find any matches " + contentA + " or " + contentB);
  }
  // 超时返回0 找到A返回1 否则返回2
  let returnVal = timeoutFlag ? 0 : findA ? 1 : 2;
  if (containContent) {
    return {
      target: target,
      bounds: target ? target.bounds() : null,
      content: res,
      value: returnVal,
    };
  } else {
    return returnVal;
  }
}

/**
 * 找到并且点击 如果返回错误就点击中心 返回一个布尔值
 * @param {str} 要找的字符串 @param {sleepTime} 查询时间 @param {waitSleep} 等待waitSleep后查询
 */
function findAndClick(str, sleepTime, waitSleep) {
  waitSleep = waitSleep || 300;
  sleep(waitSleep);
  sleepTime = sleepTime || 8000;
  let widgetGet = widgetGetOne(str, sleepTime);
  if (widgetGet) {
    log("点击:" + str);
    clickView(widgetGet);
    return widgetGet;
  }
  return false;
}

function clickView(obj) {
  try {
    let clickSuccessful = false;
    let originalObj = obj; // 保存最初的控件
    clickCenter(originalObj); // 点击最初的控件的中心位置
    sleep(1000);
    for (let i = 0; i < 4; i++) {
      if (originalObj && originalObj.clickable) {
        if (originalObj.click()) {
          clickSuccessful = true;
          break;
        }
      } else {
        originalObj = originalObj && originalObj.parent();
      }
    }
    clickSuccessful ? console.log("Control clicked successfully") : console.log("Control not clickable, checking parent");
    sleep(500);
  } catch (error) {
    console.error("按键点击失败：" + error);
  }
}

function swipex(speed) {
  let millis = parseInt(speed) || 500;
  let x = parseInt(width / 2);
  let startPoint = height - 350;
  // 滑动距离，二分之一屏幕
  let distance = parseInt(height / 3);
  let endPoint = startPoint - distance;
  // 手势上划
  log("手势上划:" + distance + " " + endPoint);
  if (全局变量 % 2 == 0) {
    swipe(x, startPoint, x + 100, endPoint, millis);
  } else {
    swipe(x, endPoint, x + 100, startPoint, millis);
  }
  全局变量++;
}

function showFLog(msgLog) {
  let str = msgLog + " ";
  setInfo(str);
}
//================悬浮窗开始================
function FloatyUtil() {
  this.floatyWindow = null;
  this.floatyInitStatus = false;
  this.floatyLock = threads.lock();
  this.floatyCondition = this.floatyLock.newCondition();
}

function init() {
  if (this.floatyInitStatus) {
    return;
  }
  let _this = this;
  threads.start(function () {
    _this.floatyLock.lock();
    try {
      if (_this.floatyInitStatus) {
        return;
      }
      _this.floatyWindow = floaty.rawWindow(
        <frame gravity="left">
          <text id="content" textSize="16dp" textColor="#00ff00" bg="#000000" alpha="0.6" />
        </frame>
      );
      ui.run(function () {
        _this.floatyWindow.setTouchable(false);
        _this.floatyWindow.setPosition(50, 50);
        _this.floatyWindow.content.text("悬浮窗初始化成功");
      });
      _this.floatyInitStatus = true;
    } catch (e) {
      console.error("悬浮窗初始化失败" + e);
      _this.floatyWindow = null;
      _this.floatyInitStatus = false;
    } finally {
      _this.floatyCondition.signalAll();
      _this.floatyLock.unlock();
    }
  });
  _this.floatyLock.lock();
  try {
    if (_this.floatyInitStatus === false) {
      console.info("等待悬浮窗初始化");
      _this.floatyCondition.await();
    }
  } finally {
    _this.floatyLock.unlock();
  }
}

function setInfo(text, position, option) {
  option = option || {};
  if (this.floatyWindow === null) {
    this.init();
  }
  let _this = this;
  ui.run(function () {
    _this.floatyLock.lock();
    try {
      if (position && isFinite(position.x) && isFinite(position.y)) {
        _this.floatyWindow.setPosition(parseInt(position.x), parseInt(position.y) + 100);
      }
      if (text) {
        _this.floatyWindow.content.text(text);
      }
      if (option.textSize) {
        _this.floatyWindow.content.setTextSize(option.textSize);
      }
      if (typeof option.touchable !== "undefined") {
        _this.floatyWindow.setTouchable(option.touchable);
      }
    } finally {
      _this.floatyLock.unlock();
    }
  });
}
//============悬浮窗结束=================
function endsWithDouble(str) {
  if (str) {
    log(str.text());
    let lastTwo = str.text().replace(/[^\d]/g, "").slice(-2);
    return lastTwo[0] !== lastTwo[1];
  }
  return false;
}

function 循环点击收取(str) {
  textContains(str)
    .find()
    .forEach((v) => {
      v.click();
      sleep(300);
    });
  sleepT(1);
  showFLog(str + "完毕");
}
function 打开支付宝农场任务列表() {
  支付宝快捷指令(支付宝农场data);
  if (!findAndClick("任务列表", 8000, 3000)) {
    killApp("com.eg.android.AlipayGphone");
    支付宝快捷指令(支付宝农场data);
    findAndClick("任务列表", 8000, 3000);
    sleepT(1);
  }
}
//这里从缓存中获取如有有值就说明今天已经助力了，不需要助力
function isStorage(action, zhifbao) {
  showFLog("本地缓存：" + storage.get(today + zhifbao + action));
  体育服务 ? 体育服务任务() : "";
  if (!storage.get(today + zhifbao + action)) {
    助力(支付宝巴巴农场助力6097, "支付宝");
    淘宝视频浏览();
    淘宝阳光农场();
    支付宝施肥();
    showFLog("今天账号：" + zhifbao + " 还没有助力，助力后缓存助力，之后今天执行就不助力");
    支付宝视频任务();
    storage.put(today + zhifbao + action, today + zhifbao + action);
  } else {
    showFLog("今天账号：" + today + zhifbao + action + " 助力过了");
  }
}

function killApp(appName) {
  var name = getPackageName(appName); //通过app名称获取包名
  if (null == name) {
    name = appName; //通过app名称获取包名
  }
  app.openAppSetting(name); //通过包名打开应用的详情页(设置页)
  if (findAndClick(/强.*|停.*|结.*/)) {
    findAndClick(/强.*|停.*|结.*/);
    findAndClick(/确定/);
  }
  home();
}

function findClickAndSwipe(action, times, sleepTime, str) {
  times = times | 10;
  sleepTime = sleepTime | 3000;
  退出当前循环 = false;
  if (str) {
    sleepT(1, "多线程退出条件：" + str);
    threads.start(function () {
      if (widgetCheck(str)) {
        showFLog("查询到退出循环条件 退出滑动浏览，查询条件：" + str);
        退出当前循环 = true;
      }
    });
  }
  if (findAndClick(action)) {
    for (let i = 1; i <= times; i++) {
      sleep(sleepTime);
      swipex();
      if (退出当前循环) {
        break;
      }
    }
    返回();
    return true;
  }
  return false;
}
function 搜索3(num) {
  if (findAndClick("去搜索", 8000, 2000)) {
    随机输入一个字符串搜索();
    findClickAndSwipe("搜索", num);
    sleep(1000);
    返回(1);
  } else {
    showFLog("没查询到去搜索");
    return true;
  }
  sleepT(2, "搜索完成等待2秒");
}
function 快捷指令(dataStr) {
  app.startActivity({
    data: dataStr,
  });
  findAndClick("允许|打开", 3000);
}
function 支付宝快捷指令(dataStr) {
  home();
  sleep(1000);
  app.startActivity({
    packageName: "com.eg.android.AlipayGphone",
    data: dataStr,
  });
  findAndClick("允许|打开", 4000);
}
function 淘宝快捷指令(dataStr) {
  app.startActivity({
    data: dataStr,
    packageName: "com.taobao.taobao",
    className: "com.taobao.browser.BrowserActivity",
  });
  findAndClick("允许|打开", 4000);
}
function 快速打开(name, packageName, className) {
  app.startActivity({
    packageName: packageName,
    className: className,
  });
  findAndClick("允许|打开", 4000);
}
function 淘宝视频浏览() {
  淘宝快捷指令(淘宝视频助力);
  sleepT(5);
  淘宝快捷指令(taobao视频浏览);
  滑动检测();
  findAndClick("立即领");
  let 立即领 = className("TextView").boundsInside(200, 1200, 900, 1600).text("立即领").findOne(6000);
  if (立即领) {
    clickCenter(立即领);
    sleepT(3);
  }
  findAndClick(".*6369.*");

  if (widgetGetOne("去提现.*|O1CN01HfQ67w1rOT9Qpsqmc_!!6000000005621-2-tps-172-68.png_200x200q75.jpg_")) {
    sleep(1000);
    循环("滑动随机等待()", 10);
    if (findAndClick("去提现.*|立即.|O1CN01HfQ67w1rOT9Qpsqmc_!!6000000005621-2-tps-172-68.png_200x200q75.jpg_")) {
      findAndClick("换现金");
      findAndClick("去签到.*");
      findAndClick("立即.*");
    }
  }
}
function 校验施肥() {
  let suzu = [];
  let shifei = textMatches(/施肥.*次/).find();
  if (shifei.length > 0) {
    shifei.forEach((v) => {
      suzu.push(v.text());
    });
    log(suzu);
    if (JSON.stringify(全局变量) == JSON.stringify(suzu)) {
      showFLog("校验施肥没变化，退出");
      return true;
    } else {
      全局变量 = suzu;
    }
  } else {
    showFLog("没有查询到施肥次数，退出");
    return true;
  }
}

function 咸鱼任务() {
  if (!currentPackage("闲鱼")) {
    return showFLog("手机未安装咸鱼应用");
  }
  app.startActivity({
    packageName: "com.taobao.idlefish",
    className: "com.taobao.fleamarket.home.activity.InitActivity",
    data: "fleamarkets://home",
  });
  findAndClick("打开|允许|.*跳过.*");
  if (!widgetCheck("我的")) {
    showFLog("没查询到控件，可能没有安装咸鱼，退出任务");
    return;
  }
  swipe(950, 400, 450, 400, 500);
  swipe(950, 400, 450, 400, 500);
  if (findAndClick("全部")) {
    sleepT(3);
    widgetCheck("全部");
    let 芭芭农场 = className("android.widget.ImageView").find();
    if (芭芭农场) {
      芭芭农场.forEach((v) => {
        if (/芭芭农场/.test(v.desc())) {
          clickCenter(v);
        }
      });
    }
    sleepT(3);
    click(900, 1600); //每日肥料
    findAndClick("关闭");
    findAndClick("集肥料", 8000, 1000);
    findAndClick("去签到", 8000, 1000);
    check去完成();
    if (findAndClick("去闲鱼.*0.1.")) {
      showFLog("到咸鱼币5s返回");
      返回(5);
    }
    findAndClick("去逛逛.*");
  }
}

function 返回(time, str) {
  sleepT(time, str);
  if (!back()) {
    sleep(400);
    back();
  }
  sleepT(1, "返回结束~~");
}
function 浏览任务(去完成) {
  log("查询到去浏览和去完成数量:" + 去完成.length);
  let 小标题 = null;
  if (去完成.length > 0) {
    for (var i = 0; i < 去完成.length; i++) {
      if (去完成[i].text() == "去签到" || 去完成[i].text() == "去领取") {
        去完成[i].click();
        sleepT(1);
        continue;
      }
      if (去完成[i].text() == "去浏览") {
        去完成[i].click();
        run_淘宝浏览15秒("任务完成");
        return;
      }
      if (去完成[i].text() == "去完成") {
        小标题 = 去完成[i].parent().child(0).child(0).text();
        showFLog(小标题);
        if (小标题 && /搜一搜|浏览|11|逛精选|去幻想|邀1|看/.test(小标题)) {
          log(去完成[i].click());
          run_淘宝浏览15秒("任务完成");
        } else {
          if (小标题 && /支付宝/.test(小标题)) {
            log(去完成[i].click());
            sleepT(5, 小标题);
            return true;
          }
          continue;
        }
        return;
      }
    }
    return true;
  }
}
function 支付宝浏览(去完成) {
  log("查询到去浏览和去完成数量:" + 去完成.length);
  if (去完成.length > 0) {
    for (var i = 0; i < 2; i++) {
      showFLog(去完成[i].text());
      let 完成 = className("android.view.View")
        .boundsInside(去完成[i].bounds().left, 去完成[i].bounds().top, 去完成[i].bounds().right, 去完成[i].bounds().bottom)
        .findOne(3000);
      if (完成) {
        let 是不是完成 = 完成.parent().child(完成.indexInParent() - 2);
        log(是不是完成);
        if (是不是完成 && /看|逛|限时/.test(是不是完成.text())) {
          去完成[i].click();
          sleepT(1);
          view("去完成|今天|去浏览；");
          校验当前页面是不是支付宝();
          break;
        }
      }
    }
  }
  if (退出当前循环) {
    showFLog("支付宝点击去浏览没反应，退出任务");
    return true;
  }
}

function 随机输入一个字符串搜索() {
  sleepT(3);
  const chars = [
    "奶嘴",
    "奶瓶",
    "纸尿裤",
    "奶粉",
    "宝宝衣服",
    "高脚椅",
    "小推车",
    "密封宝宝药箱",
    "哺乳枕",
    "吸奶器内衣",
    "安抚奶嘴",
    "背巾",
    "新生儿衣物",
    "防胀气奶瓶",
    "一次性内裤",
    "跳绳",
    "儿童滑雪鞋",
    "浮水板",
  ];
  // 获取随机索引
  const randomIndex = Math.floor(Math.random() * chars.length);
  // 根据索引获取随机字符
  const randomChar = chars[randomIndex];
  input(randomChar);
  showFLog("输入框中输入:" + randomChar);
  sleepT(1);
}
function 校验当前页面是不是支付宝() {
  if (currentPackage() != "com.eg.android.AlipayGphone") {
    showFLog("没在支付宝，启动支付宝");
    launch("com.eg.android.AlipayGphone");
  }
}
function 悬浮球模版变化() {
  threads.start(function () {
    sleep(3000);
    let 关闭 = className("android.widget.Button").text("关闭").findOne(5000);
    if (关闭) {
      clickCenter(关闭);
    }
    sleep(10000);
    let classnamenus = text("悬浮球模版").visibleToUser().findOne(8000);
    if (classnamenus) {
      try {
        classnamenus.child(1).child(0).child(0).child(0);
      } catch (error) {
        showFLog("悬浮球模版变化了，退出");
        退出当前循环 = true;
      }
    }
  });
}
function getVariableName(obj) {
  for (var prop in this) {
    if (this[prop] === obj) {
      return prop;
    }
  }
  return null;
}

function idAndClick(str, sleepTime) {
  sleepTime = sleepTime || 8000;
  let widgetGet = widgetGetById(str, sleepTime);
  if (widgetGet) {
    clickView(widgetGet);
    return widgetGet;
  }
  return false;
}

function sleepT(num, str) {
  str = str || "";
  num = num || 1;
  for (let index = num; index > 0; index--) {
    showFLog("等待结束倒计时：" + index + "秒 " + str);
    sleep(1000);
  }
}

function 循环(str, num) {
  for (let i = 0; i < num; i++) {
    showFLog("循环次数" + num + " 当前：" + i);
    if (eval(str)) {
      showFLog("满足退出条件，退出");
      break;
    }
  }
}

/**
 *
 * @param {正则表达/str/} str
 * @param {取值范围，起点+图片长宽} region
 * @param {} regex
 * @returns
 */
function 找字(str, region, regex) {
  region = region || [];
  let 当前页面截图 = images.captureScreen();
  let recognizeText = qq.recognizeWithBounds(当前页面截图, region, regex);
  log("文字查询结果：" + recognizeText.length);
  if (recognizeText.length == 0) {
    当前页面截图 = images.captureScreen();
    recognizeText = qq.recognizeWithBounds(当前页面截图, region, regex);
    log("第二次文字查询结果：" + recognizeText.length);
  }
  当前页面截图.recycle();
  for (let v of recognizeText) {
    log(v.bounds + "  " + v.label);
    if (str.test(v.label)) {
      console.info(v.label);
      log(
        "位置识别位置" +
          (Math.floor((v.bounds.right + v.bounds.left) / 2).toString() + " " + Math.floor((v.bounds.top + v.bounds.bottom) / 2).toString())
      );
      let p = { x: Math.floor((v.bounds.right + v.bounds.left) / 2), y: Math.floor((v.bounds.top + v.bounds.bottom) / 2) };
      return p;
    }
  }
}
function 施肥次数(施肥位置, num) {
  log(num);
  for (var i = 0; i < num; i++) {
    click(500 + random(0, 80), 施肥位置);
    sleep(random(500, 700));
    showFLog("自动施肥:" + i);
    if (text("好的").exists()) {
      findAndClick("好的"); //升级时候出现
    }
    if (textMatches("今天|确定|访问被拒绝|领取|去完成|点击.*").exists()) {
      let 点击按键集合 = textMatches("今天|确定|访问被拒绝|领取|去完成|点击.*").findOne(5000);
      if (点击按键集合) {
        console.info("出现:" + 点击按键集合.text() + ",施肥结束");
        if (/点击/g.test(点击按键集合.text())) {
          console.error("施肥中出现点击任务,任务应该没有做完");
          clickCenter(点击按键集合);
          view();
          continue;
        }
      }
      break;
    }
  }
}
function 去淘宝施肥20次(施肥位置) {
  支付宝快捷指令(支付宝农场data);
  let 施肥次数查询 = widgetGetOne(".*次.", 16000);
  if (施肥次数查询) {
    let num = 施肥次数查询.text().replace(/次>/, "");
    log(num);
    if (num > 0 && num < 200) {
      // let 返回点 = 找字(/键施肥/, [width / 4, height - 700, width / 3, 400]);
      let 返回点 = 找字(/键施肥/);
      log(返回点);
      if (返回点) {
        log(click(返回点.x, 返回点.y));
      } else {
        return;
      }
      施肥次数(施肥位置, 199 - num);
      log(click(返回点.x, 返回点.y));
      //到淘宝芭芭农场施肥20次
      淘宝快捷指令(淘宝巴巴农场页面);
      let 背包 = widgetGetOne("背包|更多", 16000);
      if (背包 && /更多/.test(背包.text())) {
        clickCenter(背包);
      } else {
        home();
        sleep(1000);
        launchApp("淘宝");
        findAndClick("背包|更多");
      }
      findAndClick(".*背包.*");
      if (!findAndClick(".*立即使用")) {
        if (!findAndClick("商.*城")) {
          循环("findAndClick('600购买')", 10);
          findAndClick("我的背包");
          findAndClick(".*立即使用");
        }
      }
    }
  }
}
function 退出() {
  home();
  sleep(1000);
  recents(); //近期任务
  findAndClick("清.全部");
  // back();
  // sleep(1000);
  // back();
  // sleep(1000);
  // back();
  // sleep(1000);
  // back();
  // sleep(1000);
  // home();
  // sleep(1000);
}
